package com.cskaoyan.mall.search.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.search.consts.SearchRetCode;
import com.cskaoyan.mall.search.dto.SearchRequest;
import com.cskaoyan.mall.search.dto.SearchResponse;
import com.cskaoyan.mall.search.form.SearchPageInfo;
import com.cskaoyan.mall.search.service.InitDataService;
import com.cskaoyan.mall.search.service.ProductSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LY
 * @since 2022/06/25 22:22
 */
@RestController
public class SearchController {

    @Autowired
    ProductSearchService productSearchService;

    @Autowired
    InitDataService initDataService;

    @GetMapping("shopping/search/init")
    public ResponseData init(){

      initDataService.initItems();

      return new ResponseUtil<>().setData(null);
    }

    @GetMapping("shopping/search/{key}")
    public ResponseData searchKeyword(@PathVariable("key") String keyword){

        SearchRequest request = new SearchRequest();

        request.setKeyword(keyword);

        SearchResponse response = productSearchService.fuzzySearch(request);

        if(SearchRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil().setData(response.getData());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    @PostMapping("shopping/search")
    public ResponseData search(@RequestBody SearchPageInfo searchPageInfo){
        SearchRequest request = new SearchRequest();

        request.setCurrentPage(searchPageInfo.getPage() - 1);
        request.setPageSize(searchPageInfo.getSize());
        request.setPriceGt(searchPageInfo.getPriceGt());
        request.setPriceLte(searchPageInfo.getPriceLte());
        request.setSort(searchPageInfo.getSort());
        request.setKeyword(searchPageInfo.getKey());

        SearchResponse response = productSearchService.search(request);

        if(SearchRetCode.SUCCESS.getCode().equals(response.getCode())){
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("total", response.getTotal());
            responseMap.put("data", response.getData());
            return new ResponseUtil().setData(responseMap);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
